package com.bwie.task;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.es.EsUser;
import com.bwie.mapper.TbUserMapper;
import com.bwie.pojo.TbUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
@Slf4j
public class SyncUserTask {



    @Autowired
    TbUserMapper tbUserMapper;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 每分钟同步mysql到es中
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void SyncUser(){
        log.info("开始同步用户信息~~~~~~~~~~~~~~~~");


        //获取索引判断索引是否存在

        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsUser.class);
        if (!indexOps.exists()){
           log.info("索引不存在，创建索引");

           //创建索引
           indexOps.create();

           //创建mapper
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }


        //从mysql中读取用户信息

        List<TbUser> tbUsers = tbUserMapper.selectList(null);
        //用户信息转到es

        for (TbUser tbUser : tbUsers) {
            EsUser esUser = BeanUtil.toBean(tbUser, EsUser.class);
            elasticsearchRestTemplate.save(esUser);
        }

        log.info("用户信息同步结束");


    }

}
